<template>
  <div class="dashboard-layout">
    <!-- 地图容器 -->
    <div class="map-container">
      <div id="map-container"></div>
    </div>

    <!-- 仪表盘侧边栏 -->
    <div class="sidebar">
      <!-- 登录状态模块 -->
      <div class="user-profile-card">
        <h3>用户中心</h3>
        <div v-if="isLoggedIn" class="profile-content">
          <img :src="user.avatar" alt="用户头像" class="avatar" />
          <p class="username">欢迎，{{ user.username }}</p>
          <button class="logout-btn" @click="logout">登出</button>
        </div>
        <div v-else class="login-prompt">
          <p>请先登录以使用更多功能</p>
          <button class="login-btn" @click="login">立即登录</button>
        </div>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <input v-model="searchQuery" @keyup.enter="handleSearch" placeholder="输入地点名称..." />
        <button @click="handleSearch">搜索</button>

        <!-- 搜索结果 -->
        <div v-if="searchResults.length > 0" class="search-results">
          <div
            v-for="(result, index) in searchResults"
            :key="index"
            @click="goToSearchResult(result)"
            class="result-item"
          >
            <div class="result-title">{{ result.title }}</div>
            <div class="result-address">{{ result.address }}</div>
          </div>
        </div>
      </div>

      <!-- 当前位置信息 -->
      <div class="location-info">
        <h3>当前位置信息</h3>
        <div class="info-item"><label>经度:</label>{{ currentPosition.lng.toFixed(6) }}</div>
        <div class="info-item"><label>纬度:</label>{{ currentPosition.lat.toFixed(6) }}</div>
        <div class="info-item"><label>地址:</label>{{ currentAddress || "点击地图获取位置" }}</div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button @click="locateMe">我的位置</button>
        <button @click="addMarkerAtCenter">添加标记</button>
        <button @click="clearMarkers">清除标记</button>
      </div>

      <!-- Hello World 组件 -->
      <div class="component-section hello">
        <h3>Hello World 组件</h3>
        <h1>{{ msg }}</h1>
        <button @click="handleClick">Change Word</button>
      </div>

      <!-- 计数器组件 -->
      <div class="component-section counter">
        <h3>计数器组件</h3>
        <div class="count-display">{{ count }}</div>
        <div class="buttons">
          <button @click="decrement">-</button>
          <button @click="increment">+</button>
        </div>
      </div>

      <!-- 二维码生成器 -->
      <div class="component-section qr-generator">
        <h3>二维码生成器</h3>
        <canvas id="canvas"></canvas>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode';

export default {
  name: 'BaiduMapDashboard',
  data() {
    return {
      map: null,
      geoc: null,
      geolocation: null,
      markers: [],
      searchQuery: '',
      searchResults: [],
      currentPosition: {
        lng: 116.404,
        lat: 39.915
      },
      currentAddress: '',
      bmapLoaded: false,

      // 登录状态数据
      isLoggedIn: false,
      user: {
        username: '',
        avatar: ''
      },

      // Hello World 数据
      msg: 'Hello World.',

      // 计数器数据
      count: 0
    };
  },
  mounted() {
    this.loadBaiduMap();
    this.generateQRCode();
  },
  methods: {
    loadBaiduMap() {
      if (window.BMap) {
        this.initMap();
        return;
      }

      const script = document.createElement('script');
      script.src = `https://api.map.baidu.com/api?v=3.0&ak=L1lNqaH4wVdDQaAsTLHgb8PJualVjk4k&callback=baiduMapInit`;
      document.head.appendChild(script);

      window.baiduMapInit = () => {
        this.bmapLoaded = true;
        this.initMap();
      };

      script.onerror = () => {
        console.error('百度地图加载失败');
      };
    },

    initMap() {
      this.map = new BMap.Map('map-container');
      const point = new BMap.Point(this.currentPosition.lng, this.currentPosition.lat);
      this.map.centerAndZoom(point, 15);
      this.map.enableScrollWheelZoom();
      this.map.enableDragging();
      this.map.enableDoubleClickZoom();

      this.map.addControl(new BMap.NavigationControl());
      this.map.addControl(new BMap.ScaleControl());
      this.map.addControl(new BMap.OverviewMapControl());

      this.geoc = new BMap.Geocoder();
      this.geolocation = new BMap.Geolocation();
      this.map.addEventListener('click', this.handleMapClick);
    },

    locateMe() {
      this.geolocation.getCurrentPosition(
        (r) => {
          if (this.geolocation.getStatus() === BMAP_STATUS_SUCCESS) {
            this.currentPosition = {
              lng: r.point.lng,
              lat: r.point.lat
            };
            this.map.panTo(r.point);
            this.clearMarkers();
            this.addMarker(r.point, '我的位置', true);
            this.getAddress(r.point);
          } else {
            alert('定位失败: ' + this.geolocation.getStatus());
          }
        },
        { enableHighAccuracy: true }
      );
    },

    addMarkerAtCenter() {
      const center = this.map.getCenter();
      const title = prompt('请输入标记名称', '自定义标记');
      if (title) {
        this.addMarker(center, title);
      }
    },

    addMarker(point, title, isLocation = false) {
      let icon = null;
      if (isLocation) {
        icon = new BMap.Icon(
          'https://api.map.baidu.com/images/markers.png',
          new BMap.Size(23, 25),
          {
            offset: new BMap.Size(10, 25),
            imageOffset: new BMap.Size(0, 0)
          }
        );
      }

      const marker = new BMap.Marker(point, { icon });
      this.map.addOverlay(marker);

      const label = new BMap.Label(title, {
        offset: new BMap.Size(20, -10)
      });
      marker.setLabel(label);

      const infoWindow = new BMap.InfoWindow(`
        <div style="padding: 10px;">
          <h4>${title}</h4>
          <p>经度: ${point.lng.toFixed(6)}</p>
          <p>纬度: ${point.lat.toFixed(6)}</p>
        </div>
      `);

      marker.addEventListener('click', () => {
        this.map.openInfoWindow(infoWindow, point);
      });

      this.markers.push(marker);
      return marker;
    },

    clearMarkers() {
      this.markers.forEach((marker) => {
        this.map.removeOverlay(marker);
      });
      this.markers = [];
    },

    handleMapClick(e) {
      this.currentPosition = {
        lng: e.point.lng,
        lat: e.point.lat
      };
      this.getAddress(e.point);
    },

    getAddress(point) {
      this.geoc.getLocation(point, (rs) => {
        const addComp = rs.addressComponents;
        this.currentAddress = `${addComp.province} ${addComp.city} ${addComp.district} ${addComp.street} ${addComp.streetNumber}`;
      });
    },

    handleSearch() {
      if (!this.searchQuery.trim()) {
        alert('请输入搜索关键词');
        return;
      }

      const localSearch = new BMap.LocalSearch(this.map, {
        renderOptions: {
          map: this.map,
          panel: null
        },
        onSearchComplete: (results) => {
          this.searchResults = [];
          const pois = results.getNumPois();

          if (pois > 0) {
            for (let i = 0; i < pois; i++) {
              const poi = results.getPoi(i);
              this.searchResults.push({
                title: poi.title,
                address: poi.address,
                point: poi.point
              });
            }
          } else {
            alert('未找到搜索结果');
          }
        }
      });

      localSearch.search(this.searchQuery);
    },

    goToSearchResult(result) {
      this.map.panTo(result.point);
      this.currentPosition = {
        lng: result.point.lng,
        lat: result.point.lat
      };
      this.currentAddress = result.address;

      this.clearMarkers();
      this.addMarker(result.point, result.title);

      this.searchResults = [];
      this.searchQuery = '';
    },

    handleClick() {
      this.msg = 'Hello Vue.';
    },

    increment() {
      this.count++;
    },

    decrement() {
      this.count--;
    },

    generateQRCode() {
      const canvas = document.getElementById('canvas');

      const options = {
        width: 200,
        errorCorrectionLevel: 'H'
      };

      QRCode.toCanvas(canvas, 'http://www.baidu.com', options, (error) => {
        if (error) {
          console.error('生成二维码失败:', error);
        } else {
          console.log('二维码生成成功!');
        }
      });
    },

    login() {
      const username = prompt('请输入用户名');
      if (username) {
        this.user = {
          username: username,
          avatar: 'https://via.placeholder.com/50' // 可替换为真实头像链接
        };
        this.isLoggedIn = true;
      }
    },

    logout() {
      this.isLoggedIn = false;
      this.user = {
        username: '',
        avatar: ''
      };
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.removeEventListener('click', this.handleMapClick);
    }
  }
};
</script>

<style scoped>
.dashboard-layout {
  display: flex;
  height: 100vh;
  font-family: 'Arial', sans-serif;
}

.map-container {
  flex: 1;
  height: 100%;
  position: relative;
}

#map-container {
  width: 100%;
  height: 100%;
}

.sidebar {
  width: 350px;
  padding: 20px;
  background-color: #f7f9fc;
  border-left: 1px solid #e1e5eb;
  overflow-y: auto;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.05);
}

.user-profile-card {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 25px;
  text-align: center;
  transition: all 0.3s ease;
}

.user-profile-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.user-profile-card h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 600;
}

.profile-content .avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin: 10px auto;
  display: block;
  object-fit: cover;
  border: 3px solid #e1e5eb;
}

.profile-content .username {
  font-weight: 600;
  margin: 15px 0;
  color: #34495e;
  font-size: 16px;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s ease;
  font-size: 14px;
}

.logout-btn:hover {
  background-color: #c0392b;
}

.login-prompt p {
  margin: 15px 0;
  color: #7f8c8d;
  font-size: 14px;
}

.login-btn {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s ease;
  font-size: 14px;
}

.login-btn:hover {
  background-color: #2980b9;
}

.search-box {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 25px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.search-box input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  margin-bottom: 10px;
  font-size: 14px;
  outline: none;
  transition: border 0.3s ease;
}

.search-box input:focus {
  border-color: #3498db;
}

.search-box button {
  width: 100%;
  padding: 10px;
  background-color: #2ecc71;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.search-box button:hover {
  background-color: #27ae60;
}

.search-results {
  margin-top: 15px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 6px;
}

.result-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background 0.2s ease;
}

.result-item:hover {
  background-color: #f8f9fa;
}

.result-item:last-child {
  border-bottom: none;
}

.result-title {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.result-address {
  color: #7f8c8d;
  font-size: 12px;
  margin-top: 5px;
}

.location-info {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.location-info h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 600;
}

.info-item {
  margin-bottom: 10px;
  font-size: 14px;
  color: #34495e;
}

.info-item label {
  display: inline-block;
  width: 50px;
  font-weight: 600;
  color: #7f8c8d;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 25px;
}

.action-buttons button {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.action-buttons button:nth-child(1) {
  background-color: #3498db;
  color: white;
}

.action-buttons button:nth-child(1):hover {
  background-color: #2980b9;
}

.action-buttons button:nth-child(2) {
  background-color: #2ecc71;
  color: white;
}

.action-buttons button:nth-child(2):hover {
  background-color: #27ae60;
}

.action-buttons button:nth-child(3) {
  background-color: #e74c3c;
  color: white;
}

.action-buttons button:nth-child(3):hover {
  background-color: #c0392b;
}

.component-section {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.component-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 600;
}

.hello h1 {
  font-size: 24px;
  color: #34495e;
  text-align: center;
  margin: 15px 0;
}

.hello button {
  width: 100%;
  padding: 10px;
  background-color: #9b59b6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.hello button:hover {
  background-color: #8e44ad;
}

.counter .count-display {
  font-size: 36px;
  text-align: center;
  margin: 15px 0;
  color: #2c3e50;
  font-weight: 600;
}

.counter .buttons {
  display: flex;
  gap: 10px;
}

.counter .buttons button {
  flex: 1;
  padding: 10px;
  font-size: 18px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.counter .buttons button:nth-child(1) {
  background-color: #e74c3c;
  color: white;
}

.counter .buttons button:nth-child(1):hover {
  background-color: #c0392b;
}

.counter .buttons button:nth-child(2) {
  background-color: #2ecc71;
  color: white;
}

.counter .buttons button:nth-child(2):hover {
  background-color: #27ae60;
}

.qr-generator {
  text-align: center;
}

.qr-generator canvas {
  margin: 0 auto;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 6px;
}
</style>